﻿#region Using Directives

using System;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web;

using QuickDev.Common;
using QuickDev.Common.Utils;
using QuickDev.Common.Audit;
using QuickDev.Localization;
using QuickDev.Web.UI.Controls;

using QuickDev.Model;
using QuickDev.Caching;
using QuickDev.BLL;
using QuickDev.Services;

#endregion

namespace QuickDev.Web.App.controls
{
    public partial class ucCustomerMemo : AdminControl
    {
        #region Constants

        private const string CONTENT_PATH = @"~/repository/customer/images/";
        private const string DOC_PATH = @"~/repository/customer/docs/";

        #endregion

        #region Member Variables

        private string _folder;
        private int orderId = 0;

        #endregion

        #region Page Events

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            Session["FCKeditor:UserFilesPath"] = CONTENT_PATH;
            base.OnInit( e );
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load( object sender , EventArgs e )
        {
            try
            {
                orderId = Utility.GetIntParameter( "orderId" );

                SetProperties();

                if ( !IsPostBack )
                {
                    LoadReturnOrderStatusDropDown();
                    LoadReturnOrderHeader( ReturnOrderHeaderCache.GetModel( orderId ) );

                    LoadReturnOrderMemos( ReturnOrderMemoCache.GetList( true , orderId ) );
                }
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( ucCustomerMemo ).Name + ".Page_Load" , ex );
                base.MasterPage.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSaveMemo control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnSaveMemo_Click( object sender , EventArgs e )
        {
            string memo = Strings.StripHTML( this.txtLogSummary.Value.Trim() );
            if ( String.IsNullOrEmpty( memo ) )
            {
                base.MasterPage.MessageCenter.DisplayFailureMessage( LocalizationUtility.GetStoreString( "MemoEmpty" ) );
            }
            else
            {
                try
                {
                    ReturnOrderMemo model = ReturnOrderMemoBLL.Insert( orderId , memo , Memberships.CurrentUserId );
                    if ( model != null && model.Id > 0 )
                    {
                        LoadReturnOrderMemos( ReturnOrderMemoCache.GetList( true , orderId ) );
                    }
                }
                catch ( System.Threading.ThreadAbortException )
                {
                    //ignore error.
                }
                catch ( Exception ex )
                {
                    Logger.Error( typeof( ucCustomerMemo ).Name + ".btnSaveMemo_Click" , ex );
                    base.MasterPage.MessageCenter.DisplayCriticalMessage( ex.Message );
                }
            }
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlReturnOrderStatus control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void ddlReturnOrderStatus_SelectedIndexChanged( object sender , EventArgs e )
        {
            try
            {
                ReturnOrderHeader currentReturnOrderHeader = ReturnOrderHeaderCache.GetModel( orderId );

                int statusId = -1;
                int.TryParse( ddlReturnOrderStatuses.SelectedValue , out statusId );
                if ( statusId > 0 )
                {
                    //Update to database
                    ReturnOrderHeader model = ReturnOrderHeaderBLL.UpdateStatus( orderId , statusId , Memberships.CurrentUserId );
                    if ( model != null )
                    {
                        // Add a memo
                        string content = String.Format( LocalizationUtility.GetStoreString( "StatusChanged" ) , ServiceUtility.GetFormattedStatus( currentReturnOrderHeader.ReturnOrderStatusId , ReturnOrderStatusCache.GetModel( currentReturnOrderHeader.ReturnOrderStatusId ).Name ) , ServiceUtility.GetFormattedStatus( model.ReturnOrderStatusId , ReturnOrderStatusCache.GetModel( model.ReturnOrderStatusId ).Name ) );
                        ReturnOrderMemo memo = ReturnOrderMemoBLL.Insert( orderId , content , Memberships.CurrentUserId );
                        if ( memo != null && memo.Id > 0 )
                        {
                            LoadReturnOrderMemos( ReturnOrderMemoCache.GetList( true , orderId ) );
                        }

                        base.MasterPage.MessageCenter.DisplaySuccessMessage( content );
                    }
                }

                //Response.Redirect( HttpContext.Current.Request.Url.ToString() );
            }
            catch ( System.Threading.ThreadAbortException ) { }
            catch ( Exception ex )
            {
                Logger.Error( typeof( ucCustomerMemo ).Name + ".ddlReturnOrderStatus_SelectedIndexChanged" , ex );
                base.MasterPage.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// Handles the Click event of the lbDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void lbDelete_Click( object sender , CommandEventArgs e )
        {
            try
            {
                int id = 0;
                if ( int.TryParse( e.CommandArgument.ToString() , out id ) && id > 0 )
                {
                    ReturnOrderMemo model = ReturnOrderMemoCache.GetModel( id );
                    if ( ReturnOrderMemoBLL.Delete( id , Memberships.CurrentUserId ) )
                    {
                        base.MasterPage.MessageCenter.DisplaySuccessMessage( string.Format( LocalizationUtility.GetText( "lblDeleted" ) , model.Memo ) );
                        LoadReturnOrderMemos( ReturnOrderMemoCache.GetList( true , orderId ) );
                    }
                    else
                    {
                        base.MasterPage.MessageCenter.DisplayFailureMessage( string.Format( LocalizationUtility.GetText( "lblDeletedFailed" ) , model.Memo ) );
                    }
                }
            }
            catch ( System.Threading.ThreadAbortException )
            {
                //ignore error.
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( ucCustomerMemo ).Name + ".lbDelete_Click" , ex );
                base.MasterPage.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// Handles the Click event of the btnRefresh control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnRefresh_Click( object sender , EventArgs e )
        {
            Response.Redirect( HttpContext.Current.Request.Url.ToString() );
        }

        /// <summary>
        /// Handles the ItemDataBound event of the dgCustomerMemos control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridItemEventArgs"/> instance containing the event data.</param>
        void dgCustomerMemos_ItemDataBound( object sender , DataGridItemEventArgs e )
        {
            if ( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
            {
                LinkButton deleteButton = e.Item.Cells[0].FindControl( "lbDelete" ) as LinkButton;
                if ( deleteButton != null )
                {
                    deleteButton.Attributes.Add( "onclick" , "return confirm(\"" + LocalizationUtility.GetText( "lblConfirmDelete" ) + "\");return false;" );
                }
            }
        }

        #endregion

        #region Methods

        #region Protected

        /// <summary>
        /// protected string FecthUpdateByText( string updateBy )
        /// </summary>
        /// <param name="updateBy">updateBy</param>
        /// <returns></returns>
        protected string FetchUpdatedByText( string updateBy )
        {
            return WebUtility.FecthUpdateByText( updateBy );
        }

        #endregion

        #region Private

        /// <summary>
        /// Sets the ReturnOrderHeaderEdit properties.
        /// </summary>
        private void SetProperties()
        {
        }

        /// <summary>
        /// LoadReturnOrderHeader( ReturnOrderHeader model )
        /// </summary>
        /// <param name="model">model</param>
        private void LoadReturnOrderHeader( ReturnOrderHeader model )
        {
            ddlReturnOrderStatuses.SelectedValue = model.ReturnOrderStatusId.ToString();
        }

        /// <summary>
        /// Loads the error logs.
        /// </summary>
        private void LoadReturnOrderMemos( List<ReturnOrderMemo> modelList )
        {
            dgCustomerMemos.DataSource = modelList;
            dgCustomerMemos.ItemDataBound += new DataGridItemEventHandler( dgCustomerMemos_ItemDataBound );
            dgCustomerMemos.Columns[0].HeaderText = LocalizationUtility.GetText( "hdrCreateDate" );
            dgCustomerMemos.Columns[1].HeaderText = LocalizationUtility.GetText( "hdrCreateBy" );
            dgCustomerMemos.Columns[2].HeaderText = LocalizationUtility.GetText( "hdrMemo" );
            dgCustomerMemos.Columns[3].HeaderText = LocalizationUtility.GetText( "hdrDelete" );
            dgCustomerMemos.DataBind();
        }

        /// <summary>
        /// Load ReturnOrderStatus for DropDown Control
        /// </summary>
        private void LoadReturnOrderStatusDropDown()
        {
            List<ReturnOrderStatus> statusCollection = ReturnOrderStatusCache.GetList( false );

            ddlReturnOrderStatuses.DataSource = statusCollection;
            ddlReturnOrderStatuses.DataValueField = "Id";
            ddlReturnOrderStatuses.DataTextField = "Name";
            ddlReturnOrderStatuses.DataBind();
        }

        #endregion

        #endregion

        #region Properties

        public string Folder
        {
            get
            {
                return _folder;
            }
            set
            {
                _folder = value;
            }
        }

        #endregion
    }
}